package com.onlyxiahui.framework.action.dispatcher.general;

import com.onlyxiahui.framework.action.dispatcher.ActionDispatcher;
import com.onlyxiahui.framework.action.dispatcher.extend.ActionMessage;
import com.onlyxiahui.framework.action.dispatcher.extend.ActionResponse;
import com.onlyxiahui.framework.action.dispatcher.extend.ArgumentBox;
import com.onlyxiahui.framework.action.dispatcher.extend.impl.DefaultArgumentBox;
import com.onlyxiahui.framework.action.dispatcher.general.config.GeneralActionDispatcher;
import com.onlyxiahui.framework.action.dispatcher.general.extend.ActionMessageResolver;

/**
 * <br>
 * Date 2019-12-03 18:03:38<br>
 * 
 * @author XiaHui [onlovexiahui@qq.com]<br>
 * @since 1.0.0
 */

public class GeneralMessageHandler {

	private ActionDispatcher actionDispatcher;
	private ActionMessageResolver actionMessageResolver;

	public GeneralMessageHandler() {
		actionDispatcher = new GeneralActionDispatcher();
	}

	public GeneralMessageHandler(ActionDispatcher actionDispatcher) {
		this.actionDispatcher = actionDispatcher;
	}

	public ActionMessageResolver getActionMessageResolver() {
		return actionMessageResolver;
	}

	public void setActionMessageResolver(ActionMessageResolver actionMessageResolver) {
		this.actionMessageResolver = actionMessageResolver;
	}

	public ActionDispatcher getActionDispatcher() {
		return actionDispatcher;
	}

	public void setActionDispatcher(ActionDispatcher actionDispatcher) {
		this.actionDispatcher = actionDispatcher;
	}

	public Object doMessage(String path, Object message, ActionResponse actionResponse, ArgumentBox argumentBox) {
		ActionMessage am = resolver(path, message, argumentBox);
		argumentBox.put(ActionResponse.class, actionResponse);
		return actionDispatcher.action(am, actionResponse, argumentBox);
	}

	public ArgumentBox getArgumentBox() {
		ArgumentBox beanBox = new DefaultArgumentBox();
		return beanBox;
	}

	public ActionMessage resolver(String path, Object data, ArgumentBox argumentBox) {
		ActionMessage am = (null == actionMessageResolver) ? null : actionMessageResolver.resolver(actionDispatcher, path, data, argumentBox);
		if (null == am) {
			am = new ActionMessageImpl();
			am.setMessage(data);
			am.setAction(path == null ? "" : path);
		}
		return am;
	}

	class ActionMessageImpl implements ActionMessage {

		Object message;
		String action;

		@Override
		public void setMessage(Object message) {
			this.message = message;
		}

		@Override
		public Object getMessage() {
			return this.message;
		}

		@Override
		public String getAction() {
			return this.action;
		}

		@Override
		public void setAction(String action) {
			this.action = action;
		}
	}
}
